package com.yh.datepickerdialogexample_yh;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private TextView showdate;
    private Button setdate;
    private int year;
    private int month;
    private int day;
    Calendar c=Calendar.getInstance(Locale.CHINA);
    Date mydate=new Date();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showdate=(TextView) this.findViewById(R.id.showtime);
        setdate=(Button) this.findViewById(R.id.setdate);

        c.setTime(mydate);

        year=c.get(Calendar.YEAR);
        month=c.get(Calendar.MONTH);
        day=c.get(Calendar.DAY_OF_MONTH);
        showdate.setText("当前日期:"+year+"-"+(month+1)+"-"+day);


        setdate.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v)
            {
                DatePickerDialog my_datePickerDialog=new DatePickerDialog(MainActivity.this,Datelistener,year,month,day);
                my_datePickerDialog.show();
            }
        });
    }
    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {

        @Override
        public void onDateSet(DatePicker v, int y, int m, int d) {
            if((c.get(Calendar.YEAR)*1000+c.get(Calendar.MONTH)*100+c.get(Calendar.DAY_OF_MONTH))>(y*1000+m*100+d)) {
                year = y;
                month = m;
                day = d;
                updateDate();
            }
            else
                Toast.makeText(getApplicationContext(),"Wrong date!",Toast.LENGTH_SHORT).show();

        }
        private void updateDate()
        {
            showdate.setText("当前日期："+year+"-"+(month+1)+"-"+day);
        }
    };
}

